const axios = require('axios');

async function loginTCF(page, username, password) {
    // 点击登录按钮
    await page.getByRole('button', { name: 'Login' }).click();
    // 填充用户名
    await page.getByPlaceholder('apac\\user_name').fill(username);
    // 填充密码
    await page.getByPlaceholder('Please Input').last().fill(password);
    // 再次点击登录按钮
    await page.getByRole('button', { name: 'Login' }).last().click();
    // 获取登录消息提示
    const message = await page.locator('.n-message__content').innerText();
    console.log('登录消息:', message);
    return message;
}

async function newJob(page) {
    const page1Promise = page.waitForEvent('popup');
    await page.getByRole('button', { name: 'New Job' }).click();
    const page1 = await page1Promise;
    return page1;
}

async function inputJobInfoByAPI(apiUrl, token, data) {
    try {
        const extractedData = data;
        for (const productData of extractedData) {
            const requestBody = {
                "status": "",
                "location": productData.location,
                "campaign": productData.campaign,
                "clientId": "",
                "csId": "",
                "rrId": "",
                "itemNo": productData.product,
                "supplier": productData['Main Supplier'],
                "dateValidation": new Date().toISOString(),
                "dateQSReceived": new Date().toISOString(),
                "dateTCFSample": new Date().toISOString(),
                "clientReference": productData.productSKU,
                "sampleDescription": productData['Product Short Description'],
                "dateDeadline": new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(), // 示例截止日期，可按需修改
                "reportNo": "",
                "itemGrouping": "",
                "poNo": "",
                "columns": {
                    "detail": [
                        
                    ],
                    "testitem": [
                        
                    ]
                },
                "testitems": [
                    
                ],
                "images": [
                    
                ],
                "extraInfo": {
                    
                }
            };

            // 发送 POST 请求
            const response = await axios.post(apiUrl, requestBody, {
                headers: {
                    "Authorization": `Bearer ${token}`,
                    'Content-Type': 'application/json'
                }
            });

            console.log(`成功创建 Job 对于产品 ${productData.product}:`, response.data);
        }
    } catch (error) {
        console.error('创建 Job 时出错:', error.message);
        throw error;
    }
}

module.exports = {
    loginTCF,
    newJob,
    inputJobInfoByAPI
};